package prototype.data;

import com.google.gson.JsonObject;
import prototype.constant.EObjectType;
import prototype.constant.data.AbstractObjectConst;
import prototype.utils.JsonUtils;

import javax.persistence.*;
import java.io.Serializable;

/**
 *
 */
@MappedSuperclass
public abstract class AbstractObject implements IJsonObject, AbstractObjectConst, Serializable {
	/**
	 * тип объекта
	 */
	private EObjectType objectType;
	/**
	 * идентификатор
	 */
	private Long id;

	protected AbstractObject() {
	}

	protected AbstractObject(Long id) {
		this.id = id;
	}

	@Column(name = S_OBJECT_TYPE)
	@Enumerated(EnumType.STRING)
	public final EObjectType getObjectType() {
		return objectType;
	}

	public final void setObjectType(EObjectType objectType) {
		this.objectType = objectType;
	}

	public final void setObjectType(String objectType) {
		this.objectType = (objectType != null) ? EObjectType.valueOf(objectType) : null;
	}

	@Id
	@Column(name = S_ID)
	@GeneratedValue(strategy = GenerationType.AUTO)
	public final Long getId() {
		return id;
	}

	public final void setId(Long id) {
		this.id = id;
	}

// ------------------------------- JSON ---------------------------------------

	public AbstractObject(final JsonObject jsonObject) {
		setObjectType(JsonUtils.getString(jsonObject, S_OBJECT_TYPE));
		this.id = JsonUtils.getLong(jsonObject, S_ID);
	}

	@Override
	public JsonObject toJsonObject() {
		final JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty(S_OBJECT_TYPE, objectType.name());
		jsonObject.addProperty(S_ID, id);
		return jsonObject;
	}

// ------------------------------ String --------------------------------------

	@Override
	public final String toString() {
		return toJsonObject().toString();
	}

	// ------------------------------ Compare -------------------------------------
	@Override
	public boolean equals(Object o) {
		boolean equals = false;
		if (this == o) {
			equals = true;
		} else if (o instanceof AbstractObject) {
			AbstractObject b = (AbstractObject) o;
			if (id != null ? id.equals(b.id) : b.id == null
					&& objectType == b.objectType)
				equals = true;
		}
		return equals;
	}

	@Override
	public int hashCode() {
		int result = objectType != null ? objectType.hashCode() : 0;
		result = 31 * result + (id != null ? id.hashCode() : 0);
		return result;
	}
}
